package com.hsd.survey.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.hsd.commons.model.HsdAccount;
import com.hsd.core.base.dao.IBaseDAO;
import com.hsd.core.base.service.impl.BaseService;
import com.hsd.core.utils.MD5;
import com.hsd.core.utils.TokenUtil;
import com.hsd.survey.SurveyConstants;
import com.hsd.survey.dao.ISurveyCommonDao;
import com.hsd.survey.model.HsdDataResearch;
import com.hsd.survey.model.HsdDataResult;
import com.hsd.survey.model.HsdModelAnswer;
import com.hsd.survey.model.HsdModelQuestion;
import com.hsd.survey.model.HsdModelSurvey;
import com.hsd.survey.model.MobileTransferSurvey;
import com.hsd.survey.service.ISurveyMobileService;
import com.hsd.survey.util.SurveyUtil;

/**
 * <p>
 * 类描述：移动端服务实现类
 * <p>
 * 创建人：Abdi
 * <p>
 * 创建时间：2013-10-23 下午08:36:10
 */
@Service
public class SurveyMobileServiceImpl extends BaseService implements ISurveyMobileService{
	@Autowired
	private ISurveyCommonDao surveyDao;
	
	/**
	 * 移动端查看服务器问卷列表情况
	 * @return
	 */
	@Override
	public JSONObject checkSurveyOut(String surveyuuids){
		// 获取问卷列表
		Map queryMap = new HashMap();
		List<HsdModelSurvey> surveyList = surveyDao.findList(HsdModelSurvey.class,queryMap);
		Map<String,String> map = new HashMap<String, String>();
		if(null != surveyuuids){
			String[] uuidArray = surveyuuids.split(",");
			for(String uuid : uuidArray){
				map.put(uuid, null);
			}
		}
		List<MobileTransferSurvey> undownload = new ArrayList<MobileTransferSurvey>();
		List<MobileTransferSurvey> download = new ArrayList<MobileTransferSurvey>();
		List<MobileTransferSurvey> passtime = new ArrayList<MobileTransferSurvey>();
		List<MobileTransferSurvey> deleted = new ArrayList<MobileTransferSurvey>();
		for(HsdModelSurvey modelSurvey : surveyList){
			String status = modelSurvey.getStatus().toString();
			MobileTransferSurvey model = new MobileTransferSurvey();
			model.setSurveyuuid(modelSurvey.getSurveyuuid());
			model.setName(modelSurvey.getName());
			if(isExist(modelSurvey.getSurveyuuid(), map)){// 本地服务器已存在此问卷
				if(SurveyConstants.DESIGN_PUBLISH_COLLECT.equals(status)){// 已下载
					model.setStatus(SurveyConstants.SURVEY_STATUS_DOWNLOAD);
					download.add(model);
				}else if(SurveyConstants.DESIGN_PUBLISH_PASSTIME.equals(status)){ //过时
					model.setStatus(SurveyConstants.SURVEY_STATUS_PASSED);
					passtime.add(model);
				}
			}else{
				if(SurveyConstants.DESIGN_PUBLISH_COLLECT.equals(status)){ // 未下载
					model.setStatus(SurveyConstants.SURVEY_STATUS_NOTDOWNLOAD);
					undownload.add(model);
				}
			}
		}
		for(String key : map.keySet()){ // 已删除
			if(null == map.get(key)){
				MobileTransferSurvey model = new MobileTransferSurvey();
				model.setStatus(SurveyConstants.SURVEY_STATUS_DELETE);
				model.setSurveyuuid(key);
				deleted.add(model);
			}
		}
		
		// 返回数据
		JSONObject surveryStatusData = SurveyUtil.getSucJson();
		surveryStatusData.put("undownload", JSONArray.fromObject(undownload));
		surveryStatusData.put("download", JSONArray.fromObject(download));
		surveryStatusData.put("passtime", JSONArray.fromObject(passtime));
		surveryStatusData.put("deleted", JSONArray.fromObject(deleted));
		return surveryStatusData;
	}
	
	/**
	 * 判断是否已经处理过
	 * @param surveyuuid
	 * @param map
	 * @return
	 */
	private boolean isExist(String surveyuuid,Map<String,String> map){
		if(null == map || map.size() == 0){
			return false;
		}
		if(map.containsKey(surveyuuid)){
			map.put(surveyuuid, "1");
			return true;
		}
		return false;
	}
	
	/**
	 * 移动端加载一份问卷内容
	 * @param surveyuuid
	 * @return
	 */
	@Override
	public JSONObject loadOneSurveyData(String surveyuuid){
		JSONObject surveyData = null;
		Map queryMap = new HashMap();
		queryMap.put("surveyuuid", surveyuuid);
		// 加载问卷
		Object survey = surveyDao.getUniqueObject(HsdModelSurvey.class, queryMap);
		if(null == survey){
			surveyData = SurveyUtil.getFailJson();
			surveyData.put("msg", "您请求的问卷不存在！");
			return surveyData;
		}
		// 加载问题
		List<HsdModelQuestion> questionList = surveyDao.findList(HsdModelQuestion.class,queryMap);
		// 加载答案
		List<HsdModelAnswer> answerList = surveyDao.findList(HsdModelAnswer.class,queryMap);
		// 返回数据
		surveyData = SurveyUtil.getSucJson();
		surveyData.put("survey", JSONObject.fromObject(survey));
		surveyData.put("questionlist", JSONArray.fromObject(questionList));
		surveyData.put("answerlist", JSONArray.fromObject(answerList));
		return surveyData;
	}
	
	/**
	 * 移动端问卷上传
	 * @param research
	 * @param resultlist
	 * @return
	 */
	@Override
	public JSONObject uploadResultData(String research,String resultlist){
		JSONObject responsData = null;
		String researchuuid = null;
		try {
			HsdDataResearch researchData = (HsdDataResearch)JSONObject.toBean(JSONObject.fromObject(research), HsdDataResearch.class);
			researchuuid = researchData.getResearchuuid();
			Map queryMap = new HashMap();
			queryMap.put("researchuuid", researchData.getResearchuuid());
			Object existData = surveyDao.getUniqueObject(HsdDataResearch.class, queryMap);

			responsData = SurveyUtil.getSucJson();
			responsData.put("researchuuid", researchData.getResearchuuid());
			
			if(null != existData){
				return responsData;
			}
			surveyDao.save(researchData);
			List<HsdDataResult> resultDataList = JSONArray.toList(JSONArray.fromObject(resultlist), HsdDataResult.class);
			surveyDao.saveOrUpdateAll(resultDataList);
		} catch (Exception e) {
			responsData = SurveyUtil.getFailJson();
			if(null != researchuuid){
				responsData.put("msg", "上传答案失败");
				responsData.put("researchuuid", researchuuid);
			}else{
				responsData.put("msg", "参数有误");
			}
			e.printStackTrace();
		}
		return responsData;
	}
	
	@Override
	public IBaseDAO getBaseDao() {
		return this.surveyDao;
	}
	/**
	 * 移动端加载一份问卷内容
	 * @param surveyuuid
	 * @return
	 */
	@Override
	public JSONObject loadUserData(String loginid){
		JSONObject userData = null;
		Map queryMap = new HashMap();
		queryMap.put("loginid", loginid);
		// 加载问卷
		HsdAccount userobj = (HsdAccount)surveyDao.getUniqueObject(HsdAccount.class, queryMap);
		if(null == userobj){
			userData = SurveyUtil.getFailJson();
			userData.put("msg", "您请求的用户信息不存在！");
			return userData;
		}
//		//针对用户生成TOKEN
//		String userToken = TokenUtil.genToken();
		
		// 返回数据
		userData = SurveyUtil.getSucJson();
		userData.put("userinfo", JSONObject.fromObject(userobj));
		return userData;
	}
	/**
	 * 移动端加载一份问卷内容
	 * @param surveyuuid
	 * @return
	 */
	@Override
	public JSONObject mobileLogin(String username,String password,String deviceid){
		JSONObject returnData = null;
		Map queryMap = new HashMap();
		queryMap.put("loginid", username);
		// 加载问卷
		HsdAccount userobj = (HsdAccount)surveyDao.getUniqueObject(HsdAccount.class, queryMap);
		if(null == userobj){
			returnData = SurveyUtil.getFailJson();
			returnData.put("msg", "该用户不存在或尚未开通！");
			return returnData;
		}else{
			if(userobj.getPassword().equalsIgnoreCase(password)){
				//密码正确
				//针对用户生成TOKEN
				String userToken = TokenUtil.genToken();
				userobj.setApptoken(userToken);
				userobj.setDeviceid(deviceid);
				surveyDao.saveObject(userobj); //保存用户信息
			}else{
				returnData = SurveyUtil.getFailJson();
				returnData.put("msg", "密码错误！");
				return returnData;
			}
		}
//		//针对用户生成TOKEN
//		String userToken = TokenUtil.genToken();
		
		// 返回数据
		returnData = SurveyUtil.getSucJson();
		returnData.put("userinfo", JSONObject.fromObject(userobj));
		return returnData;
	}
	
}
